package com.example.museum.controller;

import com.example.museum.common.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("files")
@RequiredArgsConstructor
public class FileController {
    
    // 上传路径，生产环境应该配置到外部存储
    private static final String UPLOAD_DIR = "src/main/resources/static/uploads/";
    
    /**
     * 上传图片
     * @param file 图片文件
     * @return 上传结果
     */
    @PostMapping("/upload")
    public Result<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failed("文件为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.failed("只支持上传图片");
        }
        
        try {
            // 确保目录存在
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成新的文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String newFilename = UUID.randomUUID() + fileExtension;

            
            // 保存文件
            Path filePath = Paths.get(UPLOAD_DIR   + newFilename);
            Files.copy(file.getInputStream(), filePath);
            
            // 返回URL
            String fileUrl = "/uploads/" + newFilename;
            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            
            return Result.success(result, "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failed("文件上传失败");
        }
    }
} 